package zhieasy.cn.xpu_helper.security.filter;

import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.Assert;
import zhieasy.cn.xpu_helper.security.token.WeChatAuthenticationToken;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author DaHang
 * @date 2020/8/14 16:03
 */
public class WeChatAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public static final String SPRING_SECURITY_FORM_WECHAT = "wechatCode";

    private String wechatParameter = SPRING_SECURITY_FORM_WECHAT;
    private boolean postOnly = true;

    public WeChatAuthenticationFilter() {
        super(new AntPathRequestMatcher("/common/wechat/login", "POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {

        if (postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException(
                "Authentication method not supported: " + request.getMethod());
        }

        //获取微信code
        String wechatCode = obtainWechatCode(request);


        if (wechatCode == null) {
            wechatCode = "";
        }

        wechatCode = wechatCode.trim();

        WeChatAuthenticationToken authRequest = new WeChatAuthenticationToken(wechatCode);

        // Allow subclasses to set the "details" property
        setDetails(request, authRequest);

        return this.getAuthenticationManager().authenticate(authRequest);
    }

    /**
     * 获取code然后通过服务器去拿unionId
     * @param request
     * @return
     */
    protected String obtainWechatCode(HttpServletRequest request) {
        return request.getParameter(wechatParameter);
    }

    protected void setDetails(HttpServletRequest request,
                              WeChatAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }

    public void setUsernameParameter(String wechatParameter) {
        Assert.hasText(wechatParameter, "wechatCode parameter must not be empty or null");
        this.wechatParameter = wechatParameter;
    }


    public void setPostOnly(boolean postOnly) {
        this.postOnly = postOnly;
    }

    public String getMobileParameter() {
        return wechatParameter;
    }

}
